<?php

namespace Budget\BudgetBundle\Controller;

use Budget\BudgetBundle\Entity\Category;
use Symfony\Component\HttpFoundation\Request;
use Budget\BudgetBundle\Form\FilterStatisticType;

class StatisticController extends MainController
{
    /**
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction(Request $request)
    {
        $family     = $this->getUser()->getFamily();
        $filterForm = $this->createForm(new FilterStatisticType());

        $data = null;
        if ($request->isMethod('post')) {
            $filterForm->submit($request);

            if ($filterForm->isValid()) {
                $data = $filterForm->getData();
            }
        }

        $avgSumList = $this->getEntityManager()
            ->getRepository('BudgetBudgetBundle:Expense')
            ->countByPeriodForFamily($family, $data);

        return $this->render('BudgetBudgetBundle:Statistic:index.html.twig', array(
            'family'     => $family,
            'avgSumList' => $avgSumList,
            'filterForm' => $filterForm->createView()
        ));
    }

    /**
     * Generates list of expenses for the family and category
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function expenseListAction(Request $request)
    {
        $params   = $request->request->all();
        $family   = $this->getUser()->getFamily();
        $category = $this->getEntityManager()
            ->getRepository('BudgetBudgetBundle:Category')->findByIdForFamily($family, $params['categoryId']);

        if (!$category instanceof Category) {
            throw new \Exception('Category not Found!');
        }

        $expenseList = $this->getEntityManager()
            ->getRepository('BudgetBudgetBundle:Expense')
            ->getAllByCategory($category, $params);

        return $this->render('BudgetBudgetBundle:Statistic:expenseList.html.twig', array(
            'family'      => $family,
            'expenseList' => $expenseList,
            'category'    => $category
        ));
    }
}